package com.xxx.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xxx.common.Result;
import com.xxx.dto.ProceedingDto;
import com.xxx.pojo.LoginUser;
import com.xxx.pojo.Matters;
import com.xxx.pojo.Proceeding;
import com.xxx.service.ProceedingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Slf4j
@RestController
@RequestMapping("/proceeding")
public class ProceedingController {

    @Autowired
    private ProceedingService proceedingService;

    /**
     * 新增事项
     * @param proceeding
     * @return
     */
    @Transactional
    @PostMapping("/save")
    @PreAuthorize("hasAnyAuthority('sys:add:proceeding')")
    public Result save(@RequestBody Proceeding proceeding){

        LocalDateTime now = LocalDateTime.now();
        proceeding.setUpdateTime(now);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String format = "SX" + now.format(formatter);

        Proceeding one = proceedingService.getOne(new LambdaUpdateWrapper<Proceeding>()
                .like(Proceeding::getId, format)
                .orderByDesc(Proceeding::getId).last("limit 1"));

        //id自增
        if (one == null) {
            format = format + "0001";
        } else {
            String id = one.getId();
            String substring = id.substring(id.length() - 4, id.length());
            Integer integer = Integer.valueOf(substring) + 1;
            //将数字转化为4位字符串
            format = format + String.format("%04d", integer);
        }
        log.info("format:{}", format);

        LoginUser principal = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        proceeding.setId(format);
        proceeding.setDepartment(principal.getUser().getDepartmentId());
        log.info("proceeding:{}",proceeding);

        boolean b = proceedingService.save(proceeding);

        return b? Result.success("保存成功") : Result.error("保存失败");

    }


    /**
     * 删除
     * @param id
     * @return
     */
    @Transactional
    @DeleteMapping("/del/{id}")
    @PreAuthorize("hasAnyAuthority('sys:deleted:proceeding')")
    public Result delById(@PathVariable String id){
        boolean b = proceedingService.removeById(id);

        return b ? Result.success("删除成功") : Result.error("删除失败");
    }

    /**
     * 修改
     * @param proceeding
     * @return
     */
    @Transactional
    @PutMapping("/update")
    @PreAuthorize("hasAnyAuthority('sys:update:proceeding')")
    public Result update(@RequestBody Proceeding proceeding){
        proceeding.setUpdateTime(LocalDateTime.now());
        boolean b = proceedingService.updateById(proceeding);

        return b ? Result.success("修改成功") : Result.error("修改失败");
    }

    /**
     * 查询
     * @param pageNo
     * @param pageSize
     * @param proceedingDto
     * @return
     */
    @PostMapping("/get-proceeding")
    @PreAuthorize("hasAnyAuthority('sys:select:proceeding')")
    public Result getByPage(Integer pageNo, Integer pageSize ,@RequestBody ProceedingDto proceedingDto){
        IPage iPage = new Page(pageNo,pageSize);

        log.info("proceedingDto:{}",proceedingDto);

        iPage = proceedingService.page(iPage, new LambdaQueryWrapper<Proceeding>()
                .like(proceedingDto.getName() != null, Proceeding::getName, proceedingDto.getName())
                .like(proceedingDto.getId() != null, Proceeding::getId, proceedingDto.getId())
                .eq(proceedingDto.getDepartment() != null, Proceeding::getDepartment, proceedingDto.getDepartment())
                .between(proceedingDto.getEndTime() != null && proceedingDto.getUpdateTime() != null, Proceeding::getUpdateTime, proceedingDto.getUpdateTime(), proceedingDto.getEndTime()));

        return Result.success("查询成功",iPage);
    }
}
